<?php
    require_once "../../config.php";
    require_once "../../functions.php";

    //获取前端传递的分类名
    $cateName = $_POST["name"];
    //连接数据库
    $connect = connect();
    //sql
    $countSql = "SELECT COUNT(id) as count FROM categories where name = '{$cateName}'";
    //执行sql语句,返回一个二维数组
    $countResult = querySelect($connect,$countSql);
    //获取根据name查询有几条数据
    $count = $countResult[0]["count"];
    //返回前端的信息提示
    $response = ["code"=>0,"msg"=>"操作失败"];

    //判断是不是有一条数据
    if($count > 0){//说明有多条
        $response["code"] = 0;
        $response["msg"] = "分类名已存在!";
    }else{
        //说明没有数据,执行插入数据的sql的语句
        // print_r($_POST);
        // Array
        //     (
        //         [name] => jack
        //         [slug] => 1
        //         [classname] => 1
        //     )
        //将post中的数据的键和值取出
        $keys = array_keys($_POST);//取出post中的键
        $keysImploed = implode(',',$keys);//以,分割
        // print_r($imploed);
        $values = array_values($_POST);
        $valuesImploed = implode("','",$values);
        // print_r($valuesImploed);
        //添加sql语句
        $addSql = "INSERT INTO categories (".$keysImploed.") VALUE('".$valuesImploed."')";
        // echo $addSql;
        //执行sql语句
        $result = mysqli_query($connect,$addSql);
        //判断是不是添加数据成功
        if($result){
            $response["code"] = 1;
            $response["msg"] = "添加数据成功";
        }

    }
    // print_r($countResult);
    header("content-type:application/json;charset=ut8");
    echo json_encode($response);
?>